package com.bwf.exception;

/**
 * @Version v1.0
 * @Description: TODO
 * @Author ZHANZHONGXIN
 * @Date 2022/5/16 14:18
 * @Copyright 博为峰
 */
public class ExceptionDemo02 {
    /*
        try{
          需要被检测异常的代码
        }catch(异常类型 变量名){
          处理异常的代码
        }catch(异常类型 变量名){
          处理异常的代码
        }
        ...
        }finally{
          一定会执行的代码
        }

        try...catch
        try...finally
     */
    public static void main(String[] args) {
        int[] arr = new int[5];
//        arr = null;
        try {
            m1(arr, -2);
        } catch (MyException e) {//MyException e = new MyException("下标不能小于0");
            String message = e.getMessage();
            System.out.println("message = " + message);
            e.printStackTrace();
            System.out.println("MyException异常已处理");
            System.exit(0);//强制退出虚拟机
        } catch (NullPointerException e) {
            System.out.println("NullPointerException异常已处理");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("ArrayIndexOutOfBoundsException异常已处理");
        } catch (Exception e) {
            System.out.println("异常已处理");
        } finally {
            //释放资源
            System.out.println("一定会执行");
        }
    }

    public static void m1(int[] arr, int index) throws MyException {
        if (arr == null) {
            throw new NullPointerException("空指针异常");
        }
        if (index >= arr.length) {
            throw new ArrayIndexOutOfBoundsException("下标越界");
        }

        if (index < 0) {
            throw new MyException("下标不能小于0");
        }
        System.out.println(arr[index]);
    }
}
